package org.crazyit.album.service.impl;

import org.crazyit.album.domain.*;
import org.crazyit.album.service.*;
import org.crazyit.album.exception.*;
import org.crazyit.album.dao.*;
import org.crazyit.album.vo.*;

import java.util.*;

public class AlbumServiceImpl implements AlbumService {

    private UserDao ud = null;
    private PhotoDao pd = null;

    public void setUserDao(UserDao ud) {
        this.ud = ud;
    }

    public void setPhotoDao(PhotoDao pd) {
        this.pd = pd;
    }


    public boolean userLogin(String name, String pass) {
        try {

            User u = ud.findByName(name);
            if (u != null && u.getPass().equals(pass)) {
                return true;
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new AlbumException(" ");
        }
    }


    public int registUser(String name, String pass) {
        try {

            User u = new User();
            u.setName(name);
            u.setPass(pass);

            ud.save(u);
            return u.getId();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new AlbumException(" ");
        }
    }

    public int addPhoto(String user, String title, String fileName) {
        try {

            Photo p = new Photo();
            p.setTitle(title);
            p.setFileName(fileName);
            p.setUser(ud.findByName(user));

            pd.save(p);
            return p.getId();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new AlbumException("");
        }
    }

    public List<PhotoHolder> getPhotoByUser(String user, int pageNo) {
        try {
            List<Photo> pl = pd.findByUser(ud.findByName(user), pageNo);
            List<PhotoHolder> result = new ArrayList<PhotoHolder>();
            for (Photo p : pl) {
                result.add(new PhotoHolder(p.getTitle(), p.getFileName()));
            }
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new AlbumException(" ");
        }
    }


    public boolean validateName(String name) {
        try {
            User u = ud.findByName(name);
            if (u != null) {
                return false;
            }
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new AlbumException(" ");
        }
    }
}